<template>
  <div>
    <el-upload
        class="upload-demo"
        action="#"
        :before-remove="beforeRemove"
        :http-request="onUpload"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <div class="upload-progress">
      <div class="value"></div>
    </div>
  </div>
</template>

<script>
import { SylUpload,getUpload, addUpload} from '@/api/updata/updata.js'
import {fileName, qieFile, hash, suffix}from "@/views/system/user/update/upload";
export default {
  name: "QiePian",
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    async onUpload({ file }) {
      let hash1 = await hash(file)
      let suffix1 = suffix(file)
      let alreadyList = [];   // 存放已上传的切片
      // 先获得已上传的切片信息  发送ajax请求
      getUpload({hash: hash1}).then(res => {
        // 将后端返回的hash名字拿到添加到alreadyList中
      }).catch(err => {})
      let chunks = qieFile(file,hash1,suffix1);  // 开始切片得到 chunks数组
      let count = chunks[0].count;
      let index = 0;
      chunks.forEach(arr => {
        // 如果有切片已经传过了那就不要在传了
        if(alreadyList.length > 0 && alreadyList.includes(arr.filename)){
          index++;   // 非常重要
          return;
        }
        // 封装成formData
        let formData = new FormData();
        formData.append('file', arr.file);
        formData.append('filename', arr.filename);
        // 发送ajax请求 上传切片
        new Promise((resolve,reject) => {
          SylUpload(formData).then(res => {
            console.log('上传成功')
            index++;// 上传成功一个记录一下
            resolve();
          }).catch(error => {
            console.log('上传失败')
            reject(error)
          })
        })
      })
      // 切片上传完毕，发起请求通知后端合成切面
      if(index > count){
        //发起请求通知后端合成切面
        addUpload({hash1: hash1,count: count}).then(res => {
          console.log('合成成功');
        }).catch(err => {
          console.log('合成失败！')
        })
      }
    }
  }
}
</script>

<style scoped>
.upload-demo {
  width: 300px;
  height: 182px;
  border: groove;
}
.upload-progress {
  width: 300px;
  height:8px;
  overflow: hidden;
  border-radius: 8px;
  background-color: #bfcbd9;
  margin-top: -10px;
}
.value {
  width: 150px;
  height:8px;
  background-color: #42b983;
}
</style>
